import datetime
import os.path
from PIL import Image
from moviepy.editor import VideoFileClip, TextClip, cvsecs
from moviepy.video.VideoClip import ImageClip
from moviepy.video.tools.subtitles import SubtitlesClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
import re


def file_to_subtitles(filename, encoding=None):
    """ Converts a srt file into subtitles.

    The returned list is of the form ``[((ta,tb),'some text'),...]``
    and can be fed to SubtitlesClip.

    Only works for '.srt' format for the moment.
    """
    times_texts = []
    current_times = None
    current_text = ""
    with open(filename, 'r', encoding=encoding) as f:
        for line in f:
            times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)
            if times:
                current_times = [cvsecs(t) for t in times]
            elif line.strip() == '':
                times_texts.append((current_times, current_text.strip('\n')))
                current_times, current_text = None, ""
            elif current_times:
                current_text += line
    return times_texts


def merge_video_and_audio(video_file, audio_file, srt_file, output, output_watermark=None, font='black.ttf',
                          font_size=30):
    # 合并视频和音频，获取视频的第一帧作为封面
    if not os.path.isfile(video_file):
        return False, "error: could not find file :{video_file}".format(video_file=video_file)
    if not os.path.isfile(audio_file):
        return False, "error: could not find file :{audio_file}".format(audio_file=audio_file)
    if not os.path.isfile(srt_file):
        return False, "error: could not find file :{srt_file}".format(srt_file=srt_file)
    video_clip = VideoFileClip(video_file)

    # 获取视频的第一帧作为封面
    video_cover = video_clip.get_frame(0)
    # 保存封面图像
    video_cover_image = Image.fromarray(video_cover)
    image_name = str(datetime.datetime.now().timestamp()).split('.')[0] + '.jpg'
    output_image_path = os.path.join(os.path.dirname(output), image_name)
    video_cover_image.save(output_image_path)


    generator = lambda txt: TextClip(txt, font=font, fontsize=font_size, color='white', stroke_color='black',
                                     stroke_width=0.5)
    subtitles = SubtitlesClip(file_to_subtitles(srt_file, 'utf-8'), make_textclip=generator)
    subtitles = subtitles.set_position(('center', video_clip.size[1] - 80))
    final_clip = CompositeVideoClip([video_clip, subtitles])
    if output_watermark:
        final_clip = add_watermark_to_video(final_clip)
        # final_clip.write_videofile(output_watermark,audio_codec="aac")
    final_clip.write_videofile(output, audio=audio_file)
    return output_image_path

def add_watermark_to_video(video_clip):
    workdir = os.getcwd()
    watermark = ImageClip(os.path.join(workdir, 'static/image/watermark.png')).set_duration(video_clip.duration)
    watermark = watermark.set_opacity(0.6)
    watermarks = [watermark.set_position(('center', 'center'))]
    # watermarks.append(watermark.set_position(('left', 'top')))
    # watermarks.append(watermark.set_position(('right', 'top')))
    # watermarks.append(watermark.set_position(('left', 'bottom')))
    # watermarks.append(watermark.set_position(('right', 'bottom')))
    return CompositeVideoClip([video_clip] + watermarks)

def convert_mov(input_file, output_file):
    # 转换mov格式
    clip = VideoFileClip(input_file)
    clip.write_videofile(output_file, write_logfile=True, codec="libx264", audio_codec="aac")